/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package luckpeople;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author Administrator
 */
public class MainFrame extends javax.swing.JFrame {

    public static final String DEFAULT_INPUT_FILE = "nameList.txt";

    public static final int OK = 0;
    public static final int FAIL = -1;

    public static final String SPLIT = ",|;|\n";

    private ArrayList<String> nameList = new ArrayList<String>();
    private boolean flagDirty = true;

    private void debugPrint(String str) {
        System.out.println(str);
    }

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();

        initData();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jFileChooser1 = new javax.swing.JFileChooser();
        jPanel1 = new javax.swing.JPanel();
        btnImport = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        btnSave = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        btnSort = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jPanel9 = new javax.swing.JPanel();
        btnRandom = new javax.swing.JButton();
        jPanel6 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea_Input = new javax.swing.JTextArea();
        jPanel8 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea_Output = new javax.swing.JTextArea();

        jFileChooser1.setCurrentDirectory(null);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("幸运抽奖");
        setFont(new java.awt.Font("楷体", 0, 18)); // NOI18N
        setResizable(false);
        java.awt.GridBagLayout layout = new java.awt.GridBagLayout();
        layout.columnWidths = new int[] {100, 200, 200};
        layout.rowHeights = new int[] {100, 100, 100, 100, 100};
        layout.columnWeights = new double[] {1.0};
        layout.rowWeights = new double[] {1.0};
        getContentPane().setLayout(layout);

        jPanel1.setLayout(new java.awt.GridLayout(1, 1));

        btnImport.setFont(new java.awt.Font("微软雅黑", 0, 18)); // NOI18N
        btnImport.setText("名单导入");
        btnImport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImportActionPerformed(evt);
            }
        });
        jPanel1.add(btnImport);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        getContentPane().add(jPanel1, gridBagConstraints);

        jPanel2.setLayout(new java.awt.GridLayout(1, 0));

        btnSave.setFont(new java.awt.Font("微软雅黑", 0, 18)); // NOI18N
        btnSave.setText("名单导出");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });
        jPanel2.add(btnSave);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        getContentPane().add(jPanel2, gridBagConstraints);

        jPanel3.setLayout(new java.awt.GridLayout(1, 0));

        btnSort.setFont(new java.awt.Font("微软雅黑", 0, 18)); // NOI18N
        btnSort.setText("名单乱序");
        btnSort.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSortActionPerformed(evt);
            }
        });
        jPanel3.add(btnSort);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        getContentPane().add(jPanel3, gridBagConstraints);

        jPanel4.setLayout(new java.awt.GridLayout(1, 0));

        jLabel1.setFont(new java.awt.Font("微软雅黑", 0, 18)); // NOI18N
        jLabel1.setText("幸运数量");
        jPanel4.add(jLabel1);

        jTextField1.setColumns(1);
        jTextField1.setFont(new java.awt.Font("微软雅黑", 0, 18)); // NOI18N
        jTextField1.setText("1");
        jPanel4.add(jTextField1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        getContentPane().add(jPanel4, gridBagConstraints);

        jPanel9.setLayout(new java.awt.GridLayout(1, 0));

        btnRandom.setFont(new java.awt.Font("微软雅黑", 0, 18)); // NOI18N
        btnRandom.setText("抽奖");
        btnRandom.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRandomActionPerformed(evt);
            }
        });
        jPanel9.add(btnRandom);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        getContentPane().add(jPanel9, gridBagConstraints);

        jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "当前名单", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("微软雅黑", 0, 18))); // NOI18N

        jTextArea_Input.setColumns(30);
        jTextArea_Input.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N
        jTextArea_Input.setRows(5);
        jTextArea_Input.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextArea_InputKeyTyped(evt);
            }
        });
        jScrollPane1.setViewportView(jTextArea_Input);

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 188, Short.MAX_VALUE)
            .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE))
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 468, Short.MAX_VALUE)
            .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 468, Short.MAX_VALUE))
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 5;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        getContentPane().add(jPanel6, gridBagConstraints);

        jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "幸运儿", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("微软雅黑", 0, 18))); // NOI18N

        jTextArea_Output.setEditable(false);
        jTextArea_Output.setColumns(30);
        jTextArea_Output.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N
        jTextArea_Output.setRows(5);
        jScrollPane2.setViewportView(jTextArea_Output);

        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
        jPanel8.setLayout(jPanel8Layout);
        jPanel8Layout.setHorizontalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 188, Short.MAX_VALUE)
            .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE))
        );
        jPanel8Layout.setVerticalGroup(
            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 468, Short.MAX_VALUE)
            .addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 468, Short.MAX_VALUE))
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 5;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        getContentPane().add(jPanel8, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnImportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImportActionPerformed
        // 弹出【打开文件】对话框
        int ret = jFileChooser1.showOpenDialog(jPanel1);
        if (ret == JFileChooser.APPROVE_OPTION) {

            // 获取要打开的文件
            File file = jFileChooser1.getSelectedFile();

            ret = importNameList(file);
            if (ret == OK) {
                showNameList();

                JOptionPane.showMessageDialog(rootPane, "OK");
            }
        }
    }//GEN-LAST:event_btnImportActionPerformed

    private void btnSortActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSortActionPerformed
        // 乱序
        if (flagDirty) {
            parseNameList(jTextArea_Input.getText());
        }

        for (int count = nameList.size(); count > 0; count--) {
            // 获取2个随机数
            int random1 = (int) (count * Math.random());
            int random2 = (int) (count * Math.random());

            String name1 = nameList.get(random1);
            String name2 = nameList.get(random2);

            // 交换顺序
            nameList.set(random1, name2);
            nameList.set(random2, name1);
        }

        // 显示在【Input】中
        showNameList();
    }//GEN-LAST:event_btnSortActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        // 弹出【保存文件】对话框
        int ret = jFileChooser1.showSaveDialog(jPanel1);
        if (ret == JFileChooser.APPROVE_OPTION) {

            // 要保存的文件
            File file = jFileChooser1.getSelectedFile();

            String nameListToString;
            if (flagDirty) {
                parseNameList(jTextArea_Input.getText());

                nameListToString = nameListToString();
            } else {
                nameListToString = jTextArea_Input.getText();
            }

            saveNameList(file, nameListToString);
            if (ret == 0) {
                jTextArea_Input.setText(nameListToString);
                JOptionPane.showMessageDialog(rootPane, "OK");
            }
        }
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnRandomActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRandomActionPerformed
        // TODO add your handling code here:
        if (flagDirty) {
            parseNameList(jTextArea_Input.getText());

            jTextArea_Input.setText(nameListToString());
        }

        int count = nameList.size();
        if (count < 1) {
            JOptionPane.showMessageDialog(rootPane, "No body! No body! No body!");
            return;
        }

        int max;
        try {
            max = Integer.parseInt(jTextField1.getText());
        } catch (Exception e) {
            e.printStackTrace();
            max = 1;
            jTextField1.setText(String.valueOf(max));
        }

        if (max < 1) {
            max = 1;
            jTextField1.setText(String.valueOf(max));
        }

        if (max > count) {
            max = count;
            jTextField1.setText(String.valueOf(max));
        }

        ArrayList<String> copy = (ArrayList<String>) nameList.clone();
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < max; i++) {
            int random = (int) ((count - i) * Math.random());

            buf.append(copy.get(random)).append("\n");
            copy.remove(random);
        }

        jTextArea_Output.setText(buf.toString());
    }//GEN-LAST:event_btnRandomActionPerformed

    private void jTextArea_InputKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextArea_InputKeyTyped
        flagDirty = true;
        debugPrint("flagDirty: " + flagDirty);

        jTextArea_Input.setBackground(Color.RED);
    }//GEN-LAST:event_jTextArea_InputKeyTyped

    /**
     * 初始化数据
     */
    private void initData() {

        // 设置打开对话框时，默认是当前路径
        String currentPath = this.getClass().getResource("").getPath();
        File file = new File(currentPath);
        jFileChooser1.setCurrentDirectory(file);

        // 如果当前路径下，有DEFAULT_INPUT_FILE，就打开该文件
        File defaultInput = new File(currentPath, DEFAULT_INPUT_FILE);
        if (defaultInput.exists()) {
            JOptionPane.showMessageDialog(rootPane, "Find DEFAULT_INPUT_FILE: " + DEFAULT_INPUT_FILE);

            int ret = importNameList(defaultInput);
            if (ret == OK) {
                // 显示在【Input】中
                showNameList();
            } else {
                jTextArea_Input.setText("Parse error DEFAULT_INPUT_FILE: " + DEFAULT_INPUT_FILE);
            }
        } else {
            jTextArea_Input.setBackground(Color.RED);
        }
    }

    /**
     * 打开文件、并解析
     *
     * @param file 待打开的文件
     * @return OK=成功，FAIL=失败
     */
    private int importNameList(File file) {
        BufferedReader reader;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainFrame.class
                    .getName()).log(Level.SEVERE, null, ex);
            return FAIL;
        }

        // 逐行读取
        StringBuilder buf = new StringBuilder();
        String str;
        try {
            while ((str = reader.readLine()) != null) {
                str = str.trim();
                if (!str.equals("")) {
                    buf.append(str).append("\n");
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class
                    .getName()).log(Level.SEVERE, null, ex);
            return FAIL;
        }

        return parseNameList(buf.toString());
    }

    /**
     * 把【Input】中的名单，保存成文件
     *
     * @param file 待保存的文件
     * @param nameListStr 当前名单
     * @return OK=成功，FAIL=失败
     */
    private int saveNameList(File file, String nameListStr) {
        BufferedWriter writer;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainFrame.class
                    .getName()).log(Level.SEVERE, null, ex);
            return FAIL;
        }

        // 写文件
        try {
            writer.write(nameListStr);
            writer.flush();
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class
                    .getName()).log(Level.SEVERE, null, ex);
            return FAIL;
        }

        return OK;
    }

    /**
     * 显示到【Input】中
     *
     * @param nameList 当前名单
     */
    private void showNameList() {
        jTextArea_Input.setText(nameListToString());
    }

    /**
     * 处理名单列表，按分割符分割、并去重
     *
     * @param origin 当前名单
     * @return
     */
    private int parseNameList(String origin) {
        nameList.clear();

        // 用HashSet来去重
        HashSet<String> set = new HashSet<String>();
        String[] array = origin.split(SPLIT);
        for (String str : array) {
            str = str.trim();
            if (!str.equals("")) {
                set.add(str);
            }
        }

        nameList.addAll(set);

        flagDirty = false;
        debugPrint("flagDirty: " + flagDirty);
        jTextArea_Input.setText(nameListToString());
        jTextArea_Input.setBackground(Color.GREEN);

        return OK;
    }

    /**
     * nameList转成字符串
     *
     * @return 字符串
     */
    private String nameListToString() {
        StringBuilder buf = new StringBuilder();

        for (String name : nameList) {
            buf.append(name).append("\n");
        }

        return buf.toString();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;

                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                MainFrame mainFrame = new MainFrame();
                mainFrame.setLocationRelativeTo(null);
                mainFrame.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnImport;
    private javax.swing.JButton btnRandom;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnSort;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea_Input;
    private javax.swing.JTextArea jTextArea_Output;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
